package main

import (
	"fmt"
	"time"
)

func main() {
	countdown0()
	fmt.Println("----")
	countdown1()
	fmt.Println("----")
	funnyChannel(1)
}

func countdown0() {
	var tick, tmout <-chan time.Time
	tick = time.Tick(time.Second)
	tmout = time.After(time.Second * 5)

loop:
	for {
		select {
		case t := <-tick:
			fmt.Printf("\r%s", t.Format("15:04:05"))
		case t := <-tmout:
			fmt.Printf("\r5 sec timeout %s\n", t.Format("15:04:05"))
			break loop
		}
	}
}

func countdown1() {
	ticker := time.NewTicker(time.Second)

	go func(tc <-chan time.Time) {
		for {
			t := <-tc
			fmt.Printf("\rticker %s", t.Format("15:04:05"))
		}
	}(ticker.C) //ticker.C is the recv-only chan

	time.Sleep(time.Second * 5)
	ticker.Stop() // ticker.Stop() will stop the goroutine which recv ticker.C
	fmt.Printf("\ntimeout\n")
}

func funnyChannel(c int) {
	ch := make(chan int, c)
	for i := 0; i < 20; i++ {
		select {
		case ch <- i:
		case x := <-ch:
			fmt.Printf("%d ", x)
		}
	}
	fmt.Println()
}
